package com.gobang.model;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserAPI {
    /**
     * 登录
     */
    @Resource
    private UserMapper userMapper;
    @PostMapping("/login")
    @ResponseBody
    public Object login(String username, String password, HttpServletRequest req) {
        User user = userMapper.selectByName(username);
        if (user == null || !user.getPassword().equals(password)) {
            return new User();
        }
        HttpSession session = req.getSession(true);
        session.setAttribute("user", user);
        return user;
    }

    /**
     * 注册
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/register")
    @ResponseBody
    public Object register(String username, String password) {
        User user = null;
        try {
            user = new User();
            user.setUsername(username);
            user.setPassword(password);
            System.out.println("register! user=" + user);
            int ret = userMapper.insert(user);
            System.out.println("ret: " + ret);
        } catch (org.springframework.dao.DuplicateKeyException e) {
            user = new User();
        }
        return user;
    }

    /**
     * 从 session 中拿到⽤⼾信息
     * @param req
     * @return
     */
    @GetMapping("/userInfo")
    @ResponseBody
    public Object getUserInfo(HttpServletRequest req) {
        // 从 session 中拿到⽤⼾信息
        HttpSession session = req.getSession(false);
        if (session == null) {
            return new User();
        }
        //拿的用户信息是登录那一刻的用户数据，而不是数据库中数据
        //登录后数据库修无法显示
        //应该从当前session中拿取数据对象
        User user = (User) session.getAttribute("user");
        User newUser = userMapper.selectByName(user.getUsername());
        if (user == null || newUser == null) {
            return new User();
        }
        return newUser;
    }
}